<template>
  <div class="table">
    <div class="container custome-container">
      <div class="handle-box custome-handle-box">
        <el-form ref="form" :rules="rules">
          <el-row style="margin-left: 0px;">
            <el-col :span="5">
              <el-form-item label="代码名称">
                <el-input v-model="select_name" placeholder="输入代码名称" style="width: 60%"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="代码类型">
                <el-input v-model="select_type" placeholder="输入代码类型" style="width: 60%"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="类别名称">
                <el-input v-model="select_title" placeholder="输入类别名称" style="width: 60%"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-button type="primary" icon="el-icon-search" @click="search"> 搜 索
              </el-button>
            </el-col>
            <el-col :span="3">
              <el-button type="info" v-has="'dicts_refresh'" icon="el-icon-pear" @click="refurbish"
              > 重 置
              </el-button>
            </el-col>
          </el-row>
          <el-row style="text-align: left;">
            <el-button type="primary" icon="el-icon-lx-add" size="mini" :disabled="readonly" @click="addNew" style="background:#3a8ee6;color:#fff;border:1px solid #3a8ee6;">添加行</el-button>
            <!--            <el-button type="success" icon="el-icon-delete" size="mini" @click="handleDeleteDetails">删除行</el-button>-->
            <el-button type="success" icon="el-icon-delete" size="mini" @click="enitNew">编辑选中行</el-button>
            <!--            <el-button type="primary" @click="clicl_Save('rulesForm')">保 存</el-button>-->
          </el-row>
        </el-form>
      </div>

      <!--新增字典-->
      <el-drawer title="新增字典(请填入默认字典项)" :visible.sync="drawerShow" :close-on-press-escape="false" :wrapperClosable="false" ref="drawer" direction="rtl" size="40%">
        <div>
          <el-form ref="newForms" :model="data" :rules="addNewRules" label-width="80px">
            <el-form-item label="代码类型" prop="dict_type" style="margin-bottom:15px;"><el-input v-model="data.dict_type"></el-input></el-form-item>
            <el-form-item label="类别名称" prop="type_name" style="margin-bottom:15px;"><el-input v-model="data.type_name"></el-input></el-form-item>
            <el-form-item label="代码值" prop="dict_code" v-show="drawerType==='add'" style="margin-bottom:15px;"><el-input v-model="data.dict_code"></el-input></el-form-item>
            <el-form-item label="代码名称" prop="dict_name" v-show="drawerType==='add'" style="margin-bottom:10px;"><el-input v-model="data.dict_name"></el-input></el-form-item>
            <el-form-item label="* 排序" v-show="drawerType==='add'" style="margin-bottom:15px;"><el-input v-model="data.dict_order" maxlength="5"></el-input></el-form-item>
            <el-form-item label="* 状态" v-show="drawerType==='add'" style="margin-bottom:15px;">
              <input type="radio" id="qiy" value="1" style="margin-left:0;margin-top: -5px;margin-right: 5px;" v-model="data.dict_status"><label for="qiy">启用</label>
              <input type="radio" id="jiny" value="0" style="margin-left:50px;margin-top: -5px;margin-right: 5px;" v-model="data.dict_status"><label for="jiny">禁用</label>
            </el-form-item>
            <el-form-item label="* 上级编号" v-show="drawerType==='add'" style="margin-bottom:15px;"><el-input v-model="data.dict_parent" maxlength="10"></el-input></el-form-item>
            <el-form-item label="* 备注" v-show="drawerType==='add'" style="margin-bottom:15px;"><el-input v-model="data.dict_remark" maxlength="100"></el-input></el-form-item>
          </el-form>
          <div class="drawer__footer" style="text-align: center;">
            <el-button @click="closeNew">取 消</el-button>
            <el-button @click="resetNewForms" v-show="drawerType==='add'" type="info" plain>重 置</el-button>
            <el-button type="primary" @click="saveNewForms">保 存</el-button>
          </div>
        </div>
      </el-drawer>
      <!-- 一级字典项列表 -->
      <ces-table
          ref="table1"
          @clickRow="clickRow"
          :tableHeight='tableHeight1'
          :that='that'
          size='small '
          class="dict-list-table"
          :isSelection='false'
          :isIndex='true'
          :isHandle='true'
          :radioSelection="true"
          :tableData='tableDatalist'
          :tableCols='tableCol'
          :isPagination='true'
          :tablePage='pagination1'
          @handleSelectionChange='handleSelectionChange1'
          @handleCurrentChange='handleCurrentChange1'
          @handleSizeChange="handleSizeChange1"
      >
      </ces-table>
      <!--   字典详情列表   -->
      <div>
        <el-form>
          <el-row style="text-align: left;">
            <el-button type="primary" icon="el-icon-lx-add" size="mini" :disabled="readonly" @click="addRow()" style="background:#3a8ee6;color:#fff;border:1px solid #3a8ee6;">添加行
            </el-button>
            <el-button type="success" icon="el-icon-delete" size="mini" @click="handleDeleteDetails">删除行</el-button>
            <el-button type="primary" @click="clicl_Save('rulesForm')">保 存</el-button>
          </el-row>
        </el-form>
      </div>
      <!--详情表格-->
      <el-form :rules="rules" ref="rulesForm">
        <el-table :data='tableData' @cell-dblclick="tableDbEdit" @current-change="handleCurrentChangetb"
                  type="selection" class="tb" style="width: 100%" border v-if="tableShow" :height="null" :max-height="tableHeight">
          <el-table-column label="选择" width="45" align="center">
            <template slot-scope="scope">
              <el-radio class="radio custome-table-radio" v-model="radio" :label="scope.$index">&nbsp;
              </el-radio>
            </template>
          </el-table-column>
          <el-table-column
              label="序号"
              width="70px">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="dict_code" label="代码值" min-width="100">
            <template slot-scope="scope">
              <el-form-item :rules='rules.dict_code' :prop="'tableData.' + scope.$index + '.dict_code'">
                <el-input placeholder="请输入代码值" v-model="scope.row.dict_code " :disabled="scope.row.disabled"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="dict_name" label="代码名称" min-width="100">
            <template slot-scope="scope">
              <el-form-item :rules='rules.dict_name' :prop="'tableData.' + scope.$index + '.dict_name'">
                <el-input placeholder="请输入代码名称" v-model="scope.row.dict_name " :disabled="scope.row.disabled"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="type_name" label="类别名称" min-width="100">
            <template slot-scope="scope">
              <el-form-item :rules='rules.type_name' :prop="'tableData.' + scope.$index + '.type_name'">
                <el-input placeholder="请输入类别名称" v-model="scope.row.type_name " :disabled="scope.row.disabled"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="dict_type" label="代码类型" min-width="100">
            <template slot-scope="scope">
              <el-form-item :rules='rules.dict_type' :prop="'tableData.' + scope.$index + '.dict_type'">
                <el-input placeholder="请输入代码类型" v-model="scope.row.dict_type " :disabled="scope.row.disabled"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="dict_order" label="排序" min-width="100">
            <template slot-scope="scope">
              <el-input placeholder="请输入序号" v-model="scope.row.dict_order " :disabled="scope.row.disabled"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="dict_status" label="状态" min-width="100">
            <template slot-scope="scope">
              <el-input placeholder="请输入状态" v-model="scope.row.dict_status " :disabled="scope.row.disabled"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="dict_time" label="录入时间" min-width="100">
            <template slot-scope="scope">
              <el-input placeholder="此项可忽略" v-model="scope.row.dict_time " :disabled="scope.row.disabled"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="dict_remark" label="备注" min-width="100">
            <template slot-scope="scope">
              <el-input placeholder="请输入备注" v-model="scope.row.dict_remark " :disabled="scope.row.disabled"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="dict_parent" label="上级编号"
                           min-width="100">
            <template slot-scope="scope">
              <el-input placeholder="请输入上级编号" v-model="scope.row.dict_parent "
                        :disabled="scope.row.disabled"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <!--      el-table分页-->
      <el-pagination
          style="display: flex;justify-content: center;height: 100%;align-items: center;margin-top: 20px;"
          id="dict-el-page"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 30, 40, 50]"
          :total="pagination.total"
          :current-page="pagination.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
      </el-pagination>

      <cesEdit :Visible="cesEditVisible" :data="form" :titleName="titleName"></cesEdit>
    </div>
  </div>
</template>

<script>
import cesTable from '../../../../components/common/Table'
import cesEdit from './edit'

export default {
  name: "demoTable",
  components: {
    cesTable,
    cesEdit
  },
  provide() {
    return {
      refresh: this.refresh, search: this.search, reLoadDict: this.reLoadDict
    }
  },
  data() {
    return {
      that: this,
      tableHeight: window.innerHeight - 10,
      tableHeight1: window.innerHeight - 650,
      //查询子字典项
      url_page: '/auth/dict/pages',
      //查询一级字典项
      url_page_jl: '/auth/dict/pagesyj',
      url_dele: '/auth/dict/dictDelete',
      url_save: '/auth/dict/dictSave',
      url_update:  '/auth/dict/dictUpdate',
      url_edit:  '/auth/dict/dictEdit',
      multipleSelection: [],
      multipleSelection1: [],
      //radio选中行的值
      currentSelectItem: '',
      currentSelectItem1: '',
      del_list: [],
      tableData1: [],
      cesEditVisible: false,
      readonly: false,
      tableDatas: [{
        rowNum: 1,
        dict_name: ' ',
        dict_type: ' ',
        type_name: '  ',
      }],
      // 简略表头及字段
      tableCol: [
        {label: '类别名称', prop: 'type_name'},
        {label: '代码类型', prop: 'dict_type'},
        // {label: '代码名称', prop: 'dict_name'},
      ],
      radio: [],
      //简略表格数据
      tableDatalist: [],
      //表格数据
      tableData: [],
      select_name: "",
      select_type: "",
      select_title: "",
      titleName: "",
      drawerShow: false,
      pagination: {
        pageSize: 10, pageNum: 1, total: 10
      },
      pagination1: {
        pageSize: 10, pageNum: 1, total: 10
      },
      data: {
        dict_pk: '',
        dict_code: '',
        dict_name: '',
        dict_type: '',
        type_name: '',
        dict_order: '',
        dict_status: '0',
        dict_time: '',
        dict_remark: '',
        dict_parent: '',
        dict_number:'',
        olddict_type:'',
        oldtype_name:''
      },
      form: {
        dict_time: '',
        dict_pk: '',
        type_name: '',
        dict_name: '',
        dict_type: '',
        dict_order: '',
        dict_code: '',
        dict_parent: '',
        dict_remark: '',
        dict_status: '',
        dict_level: '',
        page: '1',//第几页
        limit: '10'//每页条数，默认10条
      },
      form1: {
        dict_name: '',
        dict_type: '',
        type_name: '',
        page: '1',//第几页
        limit: '10'//每页条数，默认10条
      },
      addNewRules: {
        // 要以数组形式展示
        dict_code: [
          { required: this.drawerType==='add', message: "请输入代码值", trigger: "change" }
        ],
        dict_name: [
          { required: this.drawerType==='add', message: "请输入代码名称", trigger: "change" },
          { min: 1, max: 100, message: "长度在 1 到 100 个字符", trigger: "blur" }
        ],
        dict_type: [
          { required: true, message: "请输入代码类型", trigger: "change" },
          { min: 1, max: 30, message: "长度在 1 到 30 个字符", trigger: "blur" }
        ],
        type_name: [
          { required: true, message: "请输入类别名称", trigger: "change" },
          { min: 1, max: 30, message: "长度在 1 到 30 个字符", trigger: "blur" }
        ]
      },
      rules: {
        // dict_code: [
        //   { required: true, message: " ", trigger: "change" },
        // ],
        // dict_name: [
        //   { required: true, message: " ", trigger: "change" },
        // ],
        // type_name: [
        //   { required: true, message: " ", trigger: "change" },
        // ],
        // dict_type: [
        //   { required: true, message: " ", trigger: "change" },
        // ],
      },
      tableShow: true,
      drawerType: 'add',
    }
  },
  created() {
    this.cesEditVisible = false;
    this.getPages();
    this.getPages_jl();
  },
  methods: {
    //编辑表格el-table
    tableDbEdit(row) {
      //开启单元格编辑
      let _this_ = this;
      this.tableData[this.tableData.indexOf(row)].disabled = false;
      _this_.tableShow = false;
      this.$nextTick(() => {
        _this_.tableShow = true;
        setTimeout(function () {
          document.getElementById("dict-el-page").scrollIntoView({behavior: 'smooth'});
        }, 10);
      })
    },
    //行变化事件
    handleCurrentChangetb(row) {
      this.currentSelectItem = row;
    },
//简略表点击行事件
    clickRow(val) {
      // this.tableDbEdit(val, column);
      if (val) {
        this.currentSelectItem1 = val;
        this.form.dict_name = val.dict_name;
        this.form.dict_type = val.dict_type;
        this.form.type_name = val.type_name;
        //执行查询详情方法并刷新简略表
        this.getPages();
        //this.getPages_jl();
        setTimeout(function () {
          document.getElementById("dict-el-page").scrollIntoView({behavior: 'smooth'});
        }, 100);
      } else {
        this.$message({type: 'warning', message: '请重新选择！！！'});
      }
      //console.log(JSON.stringify(val))
    },
    // 增加行
    addRow() {
      if (this.currentSelectItem1){
        let list = {
          dict_code: '',
          dict_name: '',
          type_name: this.form.type_name,
          dict_type: this.form.dict_type,
          dict_order: '',
          dict_pk: '',
          dict_time: '',
          dict_parent: '',
          dict_remark: '',
          dict_level: '',
          dict_status:''
        }
        this.tableData.unshift(list);
      }else{
        this.$message({type: 'warning', message: '请选择上方字典代码类型！'});
      }
    },
    // 删除选中行
    handleDeleteDetails() {
      let _this_ = this;
      let row = this.currentSelectItem;
      if (row) {
        let pkid = row.dict_pk;
        this.$confirm('确定要删除数据吗？', '提示', {
          confirmButtonText: '确定', cancleButtonText: '取消', type: 'warning'
        }).then(() => {
          debugger;
          this.$post(this.url_dele, {dict_pks: pkid}).then(res => {
            debugger;
            this.$message({type: res.code, message: res.msg,});
            _this_.currentSelectItem = [];
            _this_.refresh();
            // _this_.reLoadDict();
          })
        }).catch(() => {
          this.getPages();
        });
      } else {
        this.$message({type: 'warning', message: '请选择一条记录！！！'});
      }
    },
    //保存数据方法
    clicl_Save() {
      debugger
      let row = this.currentSelectItem;
      this.tableData[this.tableData.indexOf(row)].disabled = true;
      let str = JSON.stringify(this.tableData);
       if (row!= null || row != undefined) {
        this.url = this.url_save
        this.form.dict_time = row.dict_time,
            this.form.dict_pk = row.dict_pk,
            this.form.type_name = row.type_name,
            this.form.dict_name = row.dict_name,
            this.form.dict_type = row.dict_type,
            this.form.dict_order = row.dict_order,
            this.form.dict_code = row.dict_code,
            this.form.dict_parent = row.dict_parent,
            this.form.dict_remark = row.dict_remark,
            this.form.dict_status = row.dict_status,
            this.form.dict_level = row.dict_level;
        console.log("success submit!!");
        this.$post(this.url, this.form).then(res => {
          this.$message({type: res.code, message: res.msg,});
          console.log(res.msg);
          this.search();
          if ("操作成功" == res.msg) {
            this.Visible = false;
            //刷新列表页的数据
            this.getPages();
            this.getPages_jl();
          }
        })
      } else {
        this.$message({
          type: 'warning',
          message: '请选择一条记录！！！'
        })
      }

    },
    //变更分页条数
    handleSizeChange(val) {
      this.form.limit = val;
      this.getPages();//根据用户获取的每页显示页面数量显示页面
    },
    //变更上一页下一页
    handleCurrentChange(val) {
      this.form.page = val;
      this.getPages()
    },

    //变更分页条数
    handleSizeChange1(val) {
      this.form.limit = val;
      this.getPages_jl();//根据用户获取的每页显示页面数量显示页面
    },
    //变更上一页下一页
    handleCurrentChange1(val) {
      this.form.page = val;
      this.getPages_jl()
    },
    //选中table行
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //选中table行
    handleSelectionChange1(val) {
      this.multipleSelection1 = val;
    },
    enitNew(){
      debugger;
      if (this.currentSelectItem1){
        this.data.dict_type = this.currentSelectItem1.dict_type;
        this.data.type_name = this.currentSelectItem1.type_name;
        this.drawerType = 'edit';
        this.drawerShow = true;
      }else{
        this.$message({type: 'warning', message: '请选择字典代码类型！'});
      }
    },
    addNew(){
      debugger
      this.drawerType='add';
      this.drawerShow = true;
    },
    closeNew(){
      if (this.drawerType === 'edit') {
        this.data.dict_type = '';
        this.data.type_name = '';
      }
      this.drawerShow = false;
    },
    saveNewForms(){
      debugger
      if(this.drawerType == 'add'){
        debugger
        this.$formValidate(this.$refs['newForms'], valid => {
          if (valid) {
            this.$post(this.url_save, this.data).then(res => {
              this.$message({type: res.code, message: res.msg,});
              if ("操作成功" === res.msg) {
                //成功以后清空表单数据
                this.data.dict_code = '';
                this.data.dict_name = '';
                this.data.dict_type = '';
                this.data.type_name = '';
                this.data.dict_number = '';
                this.data.dict_order = '';
                this.search();
                this.$refs.drawer.closeDrawer();
              }
            })
          }else{
            console.log("error submit!!");
            return false;
          }
        })
      }else  if(this.drawerType == 'edit'){
        debugger;
        //编辑字典项
        console.log("进入编辑方法!!");
        this.$formValidate(this.$refs['newForms'], valid => {
          if (valid) {
            this.data.olddict_type= this.currentSelectItem1.dict_type;
            this.data.oldtype_name=this.currentSelectItem1.type_name;
            this.$post(this.url_edit, this.data).then(res => {
              this.$message({type: res.code, message: res.msg,});
              if ("操作成功" === res.msg) {
                this.$message({type: 'warning', message: '操作成功！'});
                //成功以后清空表单数据
                this.data.dict_type = '';
                this.data.type_name = '';
                this.search();
                this.$refs.drawer.closeDrawer();
              }
            })
          }else{
            this.$message({type: 'warning', message: '操作失败！'});
            console.log("error submit!!");
            return false;
          }
        })
      }

    },
    resetNewForms(){
      for(var key in this.data){
        this.data[key]='';
      }
    },
    // 获取分页的模拟数据
    getPages() {
      this.disInput = [];
      this.cesEditVisible = false;
      this.form.limit = this.pagination.pageSize;
      if (this.form.dict_type != null) {
        this.form.dict_type = this.form.dict_type.toUpperCase();
      }
      this.tableData = [];
      this.pagination.total = 0;
      this.$post(this.url_page, this.form).then(res => {
        if (res.data) {
          this.radio = [];
          this.tableData = res.data;
          this.pagination.total = res.data.total;
          for (let i = 0; i < this.tableData.length; i++) {
            this.tableData[i].disabled = true;
          }
        }
      })
    },
    // 获取 easy-mock 的模拟数据
    getPages_jl() {
      this.cesEditVisible = false;
      // this.form1.page = this.pagination1.pageNum;
      this.form1.limit = this.pagination1.pageSize;
      if (this.form1.dict_type) {
        this.form1.dict_type = this.form1.dict_type.toUpperCase();
      }
      try {
        this.$refs.table1.clearRadioSelection();
      }catch (e) {/**/}
      this.tableDatalist = [];
      this.currentSelectItem1 = '';
      this.pagination1.total = 0;
      this.$post(this.url_page_jl, this.form).then(res => {
        if (res.data) {
          this.tableDatalist = res.data;
          this.pagination1.total = res.data.total;
        }
      })
    },
    //搜索
    search() {
      this.form = {page: '1', limit: '10'};
      this.form.dict_name = this.select_name;
      this.form.dict_type = this.select_type;
      this.form.type_name = this.select_title;
      //this.getPages();
      this.tableData = [];
      this.pagination.total = 0;
      this.getPages_jl();
    },
    refresh() {
      this.cesEditVisible = false;
      this.form = {page: '1', limit: '10'};
      this.getPages_jl();
      this.getPages();
    },
    //重置
    refurbish() {
      this.cesEditVisible = false;
      this.select_name = "";
      this.select_type = "";
      this.select_title = "";
      this.form = {page: '1', limit: '10'};
      this.getPages();
      this.getPages_jl();
    },
    //单个删除
    handleDelete(index, row) {
      if (row.dict_pk != null && row.dict_pk != "") {
        this.$confirm('确定要删除数据吗？', '提示', {
          confirmButtonText: '确定', cancleButtonText: '取消', type: 'warning'
        }).then(() => {
          this.$post(this.url_dele, {dict_pks: row.dict_pk}).then(res => {
            this.$message({type: 'success', message: res.msg,});
            this.reLoadDict();
            this.getPages();
          })
        })
      }
    },
    /*重新加载字典*/
    reLoadDict() {
      this.$getAllDic();
    }
  },
  /*全页面监听回车查询事件*/
  mounted() {
    let _this = this
    document.onkeydown = function (e) {
      if (e.keyCode === 13) {
        _this.search();
      }
    }
  }
};
</script>


<style scoped>
@import "../../../../assets/css/common.css";
</style>